// pages/card-center/chat/caht.js

const TIM = require("../../../components/tim/tim-wx");
const util = require('../../../utils/util');
const requestUtil = require('../../../utils/request');
const api = require('../../../config/api');
const timConst = require("../../../config/const");
const app = getApp();

let tim = wx.$TIM;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIMlogin: false, // im是否已登录
    conversationID: '', // 会话id
    nextReqMessageID: '', // 用于获取消息列表分页续拉的字段,
    isCompleted: false, // 是否已读取完消息列表，false - 可继续读， true - 已读完
    inputValue: '', // 输入的值
    scrollTop: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;

    this.addUser();

    tim.setLogLevel(0);
    // tim.registerPlugin({
    //   'tim-upload-plugin': TIMUploadPlugin
    // });

    this.setData({
      userId: options.id,
      conversationID: 'C2C' + "E" + options.id
    });

    this.im_on();
    _this.getMessageList();
  },

  onReady: function () {
    this.setMessageRead();
  },

  /**
   * 下拉触顶事件
   */
  onRefresh: function () {
    if (!this.data.isCompleted) {
      this.getMessageList(true);
    } else {
      util.showToast('没有更多记录了');
    }
  },

  /**
   * 添加当前用户到腾讯云平台
   * 
   * 理论上不应该这样做，不然每次发起聊天都会添加一次。
   * 不过腾讯云的添加机制是同一ID只会添加一次，重复添加没用，所以无所谓了
   */
  addUser: async function () {
    let random = parseInt(Math.random() * 10000);
    let url = 'https://console.tim.qq.com/v4/im_open_login_svc/account_import' + '?sdkappid=' + timConst.TimOptions.SDKAppID + '&identifier=admin' + '&usersig=' + app.globalData.adminSig + '&random=' + random + '&contenttype=json';
    let data = {
      Identifier: 'C' + app.globalData.customInfo.id.toString(),
      Nick: app.globalData.customInfo.name
    }
    let res = await requestUtil.request("POST", url, data);
    if (res.data.ActionStatus == 'FAIL') {
      console.error('添加用户失败，ErrorCode：' + res.data.ErrorCode);
      console.error('ErrorInfo：' + res.data.ErrorInfo);
    } else {
      console.log('----------添加单个用户')
    }
  },

  /**
   * 获取消息列表
   */
  getMessageList: function (flag = false) {
    let _this = this;
    if (!flag) {
      let promise = tim.getMessageList({
        conversationID: _this.data.conversationID,
        count: 15
      });
      promise.then(function (imResponse) {
        const messageList = imResponse.data.messageList; // 消息列表。
        const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        for (let list of messageList) {
          let num = util.subtractTimeStampToDay(list.time, Date.parse(new Date()) / 1000);
          if (num == 0) {
            list.trueTime = util.formatMinDay(new Date(list.time * 1000));
          } else {
            list.trueTime = util.formatTimeNoSecond(new Date(list.time * 1000));
          }
        }
        _this.setData({
          messageList,
          nextReqMessageID,
          isCompleted
        })
        _this.setBottom();
      });
    } else {
      let promise = tim.getMessageList({
        conversationID: _this.data.conversationID,
        nextReqMessageID: _this.data.nextReqMessageID,
        count: 15
      });
      promise.then(function (imResponse) {
        const messageList = imResponse.data.messageList; // 消息列表。
        const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        for (let mes of messageList) {
          let num = util.subtractTimeStampToDay(mes.time, Date.parse(new Date()) / 1000);
          if (num == 0) {
            mes.trueTime = util.formatMinDay(new Date(mes.time * 1000));
          } else {
            mes.trueTime = util.formatTimeNoSecond(new Date(mes.time * 1000));
          }
        }
        let list = _this.data.messageList;
        list.push(...messageList);
        _this.setData({
          messageList: list,
          nextReqMessageID,
          isCompleted
        })
        _this.setBottom();
      });
    }
  },

  /**
   * 更新事件跳入这里，获取list并添加到data里
   */
  setMessageList: function (list) {
    let _this = this;
    for (let l of list) {
      let num = util.subtractTimeStampToDay(l.time, Date.parse(new Date()) / 1000);
      if (num == 0) {
        l.trueTime = util.formatMinDay(new Date(l.time * 1000));
      } else {
        l.trueTime = util.formatTimeNoSecond(new Date(l.time * 1000));
      }
    }
    let messageList = _this.data.messageList;
    messageList.push(...list);
    _this.setData({
      messageList: messageList
    })
    _this.setBottom();
  },

  /**
   * 设置所有未读消息已读
   */
  setMessageRead: function () {
    let _this = this;
    let promise = tim.setMessageRead({
      conversationID: _this.data.conversationID
    });
    promise.then(function (imResponse) {
      // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
      console.log('----------设置已读成功')
    }).catch(function (imError) {
      // 已读上报失败
      console.warn('setMessageRead error:', imError);
    });
  },

  /**
   * 创建文本消息
   * 
   */
  createTextMessage: function () {
    let message = tim.createTextMessage({
      to: 'E' + this.data.userId,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        text: this.data.inputValue
      },
    });
    this.sendMessage(message)
  },

  /**
   * 发送消息
   */
  sendMessage: function (message) {
    let _this = this;
    let promise = tim.sendMessage(message);
    promise.then(res => {
      console.log('----------发送成功', res)
      if (res.code == 0) {
        // 如果发送文本信息，则清空输入框
        if (res.data.message.type == TIM.TYPES.MSG_TEXT) {
          _this.setData({
            inputValue: ''
          });
          let mes = res.data.message;
          let num = util.subtractTimeStampToDay(mes.time, Date.parse(new Date()) / 1000);
          if (num == 0 || num == -1) {
            mes.trueTime = util.formatMinDay(new Date(mes.time * 1000));
          } else {
            mes.trueTime = util.formatTimeNoSecond(new Date(mes.time * 1000));
          }
          let list = _this.data.messageList;
          list.push(mes)
          _this.setData({
            messageList: list
          })
          _this.setBottom();
        }
      }
    }).catch(error => {
      console.error('----------发送消息失败', error)
    })

  },

  /**
   * 获取焦点
   */
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  setBottom: function () {
    // 设置屏幕自动滚动到最后一条消息处
    let that = this;
    wx.createSelectorQuery().select('#viewMessageBody').boundingClientRect(function (rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  },

  /**
   * 监听IM是否启动
   */
  im_on: function () {
    let _this = this;

    console.log('监听IM中-------------------------');

    tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
      console.log('----------收到推送的单聊、群聊、群提示、群系统通知的新消息', event.data)
      console.log('1');
      _this.setMessageList(event.data)
    })
  },
})